//
//  HTTPRequest.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/21.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import Alamofire

struct HTTPRequestError: Error {
    
}

class HTTPRequest: NSObject {
    
    struct File {
        let data: Data
        let name: String
        let fileName: String
        let mimeType: String
    }
    
    static func addToken () -> (String){
        return User.info()?.token ?? ""
    }
    
    
    static func addHeader () ->([String : String]){
        return ["version": UIDevice.current.appVersion() ,
                "cid": "100002",
                "device-type": UIDevice.current.modeName() + "/" + UIDevice.current.systemVersion,
                "token":addToken()]
    }

    class func request(_ URIString: String,
                       parameters: Parameters? = nil,
                       success: @escaping (Any) -> (),
                       failure: @escaping (Error) -> ()) {
        
        let URLString = kServerName + URIString
        
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        }
        
        Alamofire.request(URLString, method: .post, parameters: parameters, headers: addHeader())
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseData { response in
                DispatchQueue.main.async {
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false
                }
                
                switch response.result {
                case .success:
                    if let data = response.result.value {
                        #if DEBUG
                        //                        let json = String(data: data, encoding: String.Encoding.utf8)
                        //                        print("request:", json ?? "---")
                        #endif
                        success(data)
                    } else {
                        failure(HTTPRequestError())
                    }
                case .failure(let error):
                    failure(error)
                }
        }
    }
    
    //上传文件
    class func upload(_ URIString: String,
                      files: [File],
                      parameters: Parameters? = nil,
                      success: @escaping (Any) -> (),
                      failure: @escaping (Error) -> ()) {
        
        let URLString = kServerName + URIString
        
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        }
        
        Alamofire.upload(multipartFormData: { multipartFormData in
            if let p = parameters {
                for (k, v) in p {
                    if let data = (v as? String)?.data(using: .utf8) {
                        multipartFormData.append(data , withName: k)
                    }
                }
            }
            
            for i in files {
                multipartFormData.append(i.data, withName: i.name, fileName: i.fileName, mimeType: i.mimeType)
            }
        }, to: URLString, headers: addHeader()) { encodingResult in
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
            }
            
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseData { response in
                    if let data = response.result.value {
                        success(data)
                    } else {
                        failure(HTTPRequestError())
                    }
                }
            case .failure(let error):
                failure(error)
            }
        }
    }
}
